package com.joolun.common.config.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 阿里云存储
 * @author ace
 */
public class AliyunCloudStorageService extends CloudStorageService {

    private OSSClient client;

    public AliyunCloudStorageService(CloudStorageConfig config) {
        this.config = config;
        //初始化
        init();
    }

    private void init(){
        client = new OSSClient(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(), config.getAliyunAccessKeySecret());
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentDisposition("inline");
            metadata.setContentType(getContType(path));
            metadata.setObjectAcl(CannedAccessControlList.PublicRead);
            client.putObject(config.getAliyunBucketName(), path, inputStream,metadata);
        } catch (Exception e){
            throw new RuntimeException("上传文件失败，请检查配置信息. " + e.getLocalizedMessage());
        }

        return config.getAliyunDomain() + "/" + path;
    }

    @Override
    public String remove(String url){
        //文件名（服务器上的文件路径）
        String host = "https://" + config.getAliyunBucketName() + "." + config.getAliyunEndPoint() + "/";
        String objectName = url.substring(host.length());

        Boolean delFlag =false;
        try {
            client.deleteObject(config.getAliyunBucketName(),objectName);
            delFlag = true;
        }catch (Exception e){
            delFlag =false;
            throw new RuntimeException("删除文件失败，请检查配置信息. " + e.getLocalizedMessage());
        }
        return delFlag ? "删除成功" : "删除失败";

    }

    //通过文件名判断并获取OSS服务文件上传时文件的contentType  默认设置jpg格式
    public String getContType(String path) {
        int lastIndexOf = StringUtils.lastIndexOf(path, ".");
    	if(lastIndexOf < 0) {
    		return "image/jpeg";
    	}
        String typeName = path.substring(lastIndexOf);
        if(StringUtils.isBlank(typeName)){
            return "image/jpeg";
        }
        if (typeName.equalsIgnoreCase(".jpeg") ||
                typeName.equalsIgnoreCase(".jpg") ||
                typeName.equalsIgnoreCase(".png")) {
//            return "image/jpeg";
            return "image/jpg";
        }
        if (typeName.equalsIgnoreCase(".gif")) {
            return  "image/gif";
        }
        if (typeName.equalsIgnoreCase(".svg")) {
            return "image/svg";
        }
        if (typeName.equalsIgnoreCase(".bmp")) {
            return "application/x-bmp";
        }
        if (typeName.equalsIgnoreCase(".tif")) {
            return "image/tiff";
        }
        if (typeName.equalsIgnoreCase(".pcx")) {
            return "image/pcx";
        }
        if (typeName.equalsIgnoreCase(".tga")) {
            return "image/tga";
        }
        if(typeName.equalsIgnoreCase(".mp4")){
            return "video/mpeg4";
        }
        return "image/jpg";
    }

	@Override
	public InputStream getObject(String url) {
		String objectName = null;
		try {
			URL u = new URL(url);
			objectName = u.getPath().substring(1);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		
		try {
			OSSObject ossObject = client.getObject(config.getAliyunBucketName(), objectName);
			return ossObject.getObjectContent();
        } catch (Exception e){
            throw new RuntimeException("上传下载失败信息. " + e.getLocalizedMessage());
        }
	}
}
